package node.decl;

import grammar.Lexer;
import grammar.MyError;
import lexical.Key;
import node.Node;
import symbol.SymbolTable;

import java.util.ArrayList;

public class ConstDecl implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    public ArrayList<Node> nodes = new ArrayList<>();

    public ConstDecl(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parseConstDecl();
    }

    private void parseConstDecl() {
        nodes.add(lexer.getCurWord()); // const
        nodes.add(lexer.getCurWord()); // int
        nodes.add(new ConstDef(lexer, table, this));
        while (lexer.isWordType(0, Key.COMMA)) {
            nodes.add(lexer.getCurWord()); // ,
            nodes.add(new ConstDef(lexer, table, this));
        }
        if (lexer.isWordType(0, Key.SEMICN)) {
            nodes.add(lexer.getCurWord()); // ;
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'i'));
        }
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<ConstDecl>\n").toString();
    }

    @Override
    public String genMidCode() {
        for (Node node : nodes) {
            if (node instanceof ConstDef) {
                node.genMidCode();
            }
        }
        return "";
    }
}
